from flask import Flask, request, render_template, jsonify
import os
import subprocess
import pandas as pd
from werkzeug.utils import secure_filename
import math
from datetime import datetime

app = Flask(__name__)

# Use absolute paths to avoid CWD-related issues
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'uploads')
STATIC_FOLDER = os.path.join(BASE_DIR, 'static')
ALLOWED_EXTENSIONS = {'csv', 'xlsx', 'xls', 'xlsm'}

os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files.get('file')
        if not file or not allowed_file(file.filename):
            return "只允许上传 .csv、.xlsx、.xls 或 .xlsm 文件", 400

        # Sanitize filename to prevent path traversal
        filename = secure_filename(file.filename)
        
        # 获取文件信息
        file_extension = filename.rsplit('.', 1)[1].lower() if '.' in filename else 'unknown'
        upload_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        original_filename = file.filename

        input_path = os.path.join(UPLOAD_FOLDER, filename)
        output_img = os.path.join(STATIC_FOLDER, 'output.png')
        summary_csv = os.path.join(BASE_DIR, 'summary.csv')

        file.save(input_path)

        # 调用 R 脚本
        try:
            # Normalize paths for R on Windows
            input_arg = os.path.abspath(input_path)
            output_arg = os.path.abspath(output_img)

            result = subprocess.run(
                ['Rscript', os.path.join(BASE_DIR, 'analysis.R'), input_arg, output_arg],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding='utf-8',
                errors='ignore'
            )
        except FileNotFoundError:
            return (
                "<h3>未找到 Rscript 可执行文件。</h3>"
                "<p>请确保已安装 R 并将 Rscript 加入系统 PATH。</p>"
            ), 500
        except Exception as exc:
            return f"<h3>调用 R 脚本时发生异常：</h3><pre>{exc}</pre>", 500

        if result.returncode != 0:
            return f"<h3>R 脚本执行错误：</h3><pre>{result.stderr}</pre>", 500

        # 加载 R 输出的 summary.csv，用于前端渲染
        try:
            df_summary = pd.read_csv(summary_csv, encoding='utf-8')
        except Exception as exc:
            try:
                # 如果 UTF-8 失败，尝试其他编码
                df_summary = pd.read_csv(summary_csv, encoding='gbk')
            except Exception as exc2:
                try:
                    df_summary = pd.read_csv(summary_csv, encoding='gb2312')
                except Exception as exc3:
                    return f"<h3>读取 R 生成的 summary.csv 失败：</h3><pre>{exc}</pre>", 500

        # 计算分页信息
        total_rows = len(df_summary)
        rows_per_page = 20  # 每页显示20行
        total_pages = math.ceil(total_rows / rows_per_page) if total_rows > 0 else 1
        
        # 获取当前页码
        page = request.args.get('page', 1, type=int)
        page = max(1, min(page, total_pages)) if total_pages > 0 else 1
        
        # 计算当前页的数据
        start_idx = (page - 1) * rows_per_page
        end_idx = min(start_idx + rows_per_page, total_rows)
        current_page_data = df_summary.iloc[start_idx:end_idx]
        
        table_html = current_page_data.to_html(classes='table table-striped', index=False, na_rep='-')

        return render_template('result.html', 
                             image_url='static/output.png', 
                             table=table_html,
                             current_page=page,
                             total_pages=total_pages,
                             total_rows=total_rows,  # 使用总行数
                             rows_per_page=rows_per_page,
                             upload_time=upload_time,
                             file_extension=file_extension.upper(),
                             original_filename=original_filename)

    return render_template('index.html')

@app.route('/get_page_data', methods=['GET'])
def get_page_data():
    try:
        page = request.args.get('page', 1, type=int)
        summary_csv = os.path.join(BASE_DIR, 'summary.csv')
        
        if not os.path.exists(summary_csv):
            return jsonify({'error': '没有找到数据文件'}), 404
            
        df_summary = pd.read_csv(summary_csv, encoding='utf-8')
        
        # 计算分页信息
        total_rows = len(df_summary)
        rows_per_page = 20  # 每页显示20行
        total_pages = math.ceil(total_rows / rows_per_page) if total_rows > 0 else 1
        
        page = max(1, min(page, total_pages)) if total_pages > 0 else 1
        
        # 计算当前页的数据
        start_idx = (page - 1) * rows_per_page
        end_idx = min(start_idx + rows_per_page, total_rows)
        current_page_data = df_summary.iloc[start_idx:end_idx]
        
        # 转换为HTML表格
        table_html = current_page_data.to_html(classes='table table-striped', index=False, na_rep='-')
        
        return jsonify({
            'table_html': table_html,
            'current_page': page,
            'total_pages': total_pages,
            'total_rows': total_rows  # 使用总行数
        })
        
    except Exception as exc:
        return jsonify({'error': str(exc)}), 500

if __name__ == '__main__':
    app.run(port=9000, debug=True)
